#include "dlghouseedit.h"
#include "ui_dlghouseedit.h"

DlgHouseEdit::DlgHouseEdit(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgHouseEdit)
{
    ui->setupUi(this);
    connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(reject()));
    ui->ledit_h_tspc->setValidator(&m_dvalidator);
    ui->ledit_tarif->setValidator(&m_dvalidator);

}

DlgHouseEdit::~DlgHouseEdit()
{
    delete ui;
}


void DlgHouseEdit::setup_connection()
{
    connect(ui->ledit_h_name, SIGNAL(textEdited(QString)), this, SLOT(data_changed()));
    connect(ui->ledit_h_tspc, SIGNAL(textEdited(QString)), this, SLOT(data_changed()));
    connect(ui->ledit_tarif, SIGNAL(textEdited(QString)), this, SLOT(data_changed()));
    connect(ui->combo_type, SIGNAL(currentIndexChanged(int)), this, SLOT(data_changed()));
    connect(ui->facilities_list_view, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(data_changed()));
    connect(ui->tedit_comments, SIGNAL(textChanged()),this, SLOT(data_changed()));

}

void DlgHouseEdit::data_to_form()
{
    ui->combo_type->clear();
   ui->combo_type->addItems(mp_dbms->get_house_types(true));
   if(mqh_data.isEmpty()) return;
   ui->label_street->setText(mp_dbms->get_street_info(mqh_data.value(FLD_HSDB_STINDEX)));
   if(mqh_data.size() < 2) return;
   ui->ledit_h_name->setText(mqh_data.value(FLD_HSDB_NAME).toString());
   ui->combo_type->setCurrentIndex(mqh_data.value(FLD_HSDB_TYPE).toInt());
   ui->ledit_h_tspc->setText(mqh_data.value(FLD_HSDB_SPC).toString());
   ui->ledit_tarif->setText(mqh_data.value(FLD_HSDB_TARIFF).toString());
   facilities_to_view(mqh_data.value(FLD_HSDB_FACILITIES));
   ui->tedit_comments->setPlainText(mqh_data.value(FLD_HSDB_COMMENTS).toString());

}

void DlgHouseEdit::form_to_data()
{
    mqh_data[FLD_HSDB_NAME] = ui->ledit_h_name->text();
    mqh_data[FLD_HSDB_TYPE] = ui->combo_type->currentIndex();
    mqh_data[FLD_HSDB_SPC ] = ui->ledit_h_tspc->text().toDouble();
    mqh_data[FLD_HSDB_TARIFF] = ui->ledit_tarif->text().toDouble();
    mqh_data[FLD_HSDB_COMMENTS] = ui->tedit_comments->toPlainText();
    mqh_data[FLD_HSDB_FACILITIES] = get_facilities_from_view();
}


void DlgHouseEdit::facilities_to_view(const QVariant &qv_data)
{
    int fac = qv_data.toInt();
    QListWidgetItem *p_item;
    for(int i=0; i<ui->facilities_list_view->count(); i++)
    {
        int mask = 1<<i;
        p_item = ui->facilities_list_view->takeItem(0);
        if(fac & mask)
            p_item->setCheckState(Qt::Checked);
        else
            p_item->setCheckState(Qt::Unchecked);
        ui->facilities_list_view->addItem(p_item);
    }
}


QVariant DlgHouseEdit::get_facilities_from_view()
{
    int fac = 0;
    QListWidgetItem *p_item;
    for(int i = 0; i<ui->facilities_list_view->count(); i++)
    {
        p_item = ui->facilities_list_view->item(i);
        fac |= (p_item->checkState())?1<<i:0;
    }
    return QVariant(fac);
}
